package com.ruoyi.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OSSUtil {

    private static String domain = "http://img.kkc.cdn.youzhi.net/";

    private static String bucket = "kkc";

    private static String endPoint = "http://oss-cn-shenzhen.aliyuncs.com";

    private static String appSecret = "eEVLUzL2WUb04yeeod20SGjJfGVaVR";

    private static String appKey = "LTAIhVNK5JTgMQG0";

    public final static long DEFAULT_MAX_AGE = 24 * 60 * 60L;

    final static Pattern fileExt = Pattern.compile("\\.(\\w+)$");

    public static String getFileExt(String file) {
        if (file == null) {
            return "";
        }
        Matcher m = fileExt.matcher(file);
        return m.find() ? m.group(1) : "";
    }

    public static String upload(byte[] bytes, String fileName, String mineType) throws IOException {
        return upload(bucket, bytes, fileName, mineType);
    }

    public static String upload(String bucket, byte[] bytes, String fileName, String mineType) throws IOException {

        OSSClient ossClient = new OSSClient(endPoint, appKey, appSecret);

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(mineType);
        metadata.setCacheControl("max-age=" + DEFAULT_MAX_AGE);
        try {
            InputStream is = new ByteArrayInputStream(bytes);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, is, metadata);
            ossClient.putObject(putObjectRequest);
        } finally {
            ossClient.shutdown();
        }

        return domain + fileName;
    }
}
